import React, { useState } from "react";

import { useNavigate, useLocation } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { Tag, Space } from "antd";
import { closeTag, setCurrentMenu } from "../../store/reducers/tab";

import "./index.css";

const MyTag = (props) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const tabList = useSelector((state) => state.tab.tabList);
  // console.log("tabList", tabList);
  const currentMenu = useSelector((state) => state.tab.currentMenu);
  const handleClose = () => {
    console.log("zhixing");
  };

  const handleCloseTag = (tag, index) => {
    console.log("zhixing", tabList);
    let length = tabList.length - 1;
    dispatch(closeTag(tag));
    if (index == length) {
      // 设置当前数据
      const currentData = tabList[index - 1];
      dispatch(setCurrentMenu(currentData));
      navigate(currentData.path);
    } else {
      // 关闭中间的tag
      if (tabList.length > 1) {
        // 如果tag至少存在一个数据的话，那么选择后一个
        const curData = tabList[index + 1];
        dispatch(setCurrentMenu(curData));
        navigate(curData.path);
      }
    }
  };
  const handleClickTag = (tag) => {
    dispatch(setCurrentMenu(tag));
    navigate(tag.path);
  };

  // tag的显示，flag为是否选中的标识
  const setTag = (flag, item, index) => {
    return flag ? (
      <Tag closeIcon onClose={() => handleCloseTag(item, index)} color="#55acee" key={item.name}>
        {item.label}
      </Tag>
    ) : (
      <Tag key={item.name} onClick={() => handleClickTag(item)}>
        {item.label}
      </Tag>
    );
  };
  return (
    <Space className="tab-box" size={[0, 8]} wrap>
      {currentMenu.name && tabList.map((item, index) => setTag(item.path === currentMenu.path, item, index))}
    </Space>
  );
};

export default MyTag;
